import MyTable from "@/components/MyTable";
import SearchHeader from "@/components/SearchHeader";
import useTable from "@/hooks/useTable";
import { Button, Form, Popconfirm, message } from "antd";
import { useMemo } from "react";
import { useConfig } from "./form.config";

import ButtonGroup from "@/components/ButtonGroup";
import { changeFamilyStatus, delFamily, getFamilyPage } from "@/services/family";
import { useRequest } from "@umijs/max";
import { StatusEnum } from "@/constants/enum";

export default () => {
  const config = useConfig();
  const [form] = Form.useForm();

  const { tableProps, reset, submit, refresh } = useTable(getFamilyPage, {
    defaultFormValues: {},
    form: form,
  });
  const {run:del} = useRequest(delFamily,{
    manual:true,
    onSuccess:()=>{
      message.success('删除成功')
      refresh()
    }
  })
  const {run:updateStatus} = useRequest(changeFamilyStatus,{
    manual:true,
    onSuccess:(res,[params])=>{
      message.success(`${StatusEnum[params?.status]}成功`)
      refresh()
    }
  })

  const columns = useMemo(() => {
    return [
      {
        title: "家庭名称",
        dataIndex: "name",
      },
      {
        title: "描述",
        dataIndex: "description",
      },
      {
        title: "创建者账号",
        dataIndex: "username",
      },
      {
        title: "状态",
        dataIndex: "status",
        render: (v) => StatusEnum[v],
      },
      {
        title: "操作",
        dataIndex: "action",
        align: "center",
        render: (_, record) => {
          const { id,status } = record || {};
          const title = status === 0 ? StatusEnum[1]:StatusEnum[0];

          return (
            <ButtonGroup>
              <Popconfirm
                placement="topLeft"
                title={`确认${title}吗？`}
                okText="确认"
                cancelText="取消"
                onConfirm={() => {
                  updateStatus({ id,status:status === 0 ? 1 : 0 })
                }}
              >
                <Button type="link">{title}</Button>
              </Popconfirm>
              <Popconfirm
                placement="topLeft"
                title={"确认删除吗？"}
                okText="确认"
                cancelText="取消"
                onConfirm={() => {
                  del(id)
                }}
              >
                <Button type="link">删除</Button>
              </Popconfirm>
            </ButtonGroup>
          );
        },
      },
    ];
  }, []);

  return (
    <>
      <div style={{ marginBottom: "16px" }}>
        <SearchHeader
          configs={config}
          form={form}
          onSubmit={submit}
          onReset={reset}
        />
      </div>
      <MyTable rowKey={"id"} columns={columns} {...tableProps} />
    </>
  );
};
